package com.qf.xiaomi.service.impl;

import com.qf.xiaomi.dao.impl.UserDaoImpl;
import com.qf.xiaomi.pojo.TbAddress;
import com.qf.xiaomi.pojo.User;
import com.qf.xiaomi.service.UserService;
import com.qf.xiaomi.utils.EmailUtils;
import com.qf.xiaomi.utils.MD5Utils;

import java.util.List;
import java.util.UUID;

/**
 * @Created by 马英超 on 2022/8/15 19:34
 * @author： 马英超
 * @version：v1.0
 * @description:
 */
public class UserServiceImpl implements UserService {


    /**
     * 用户注册
     * @param user
     * @return boolean
     */
    @Override
    public boolean registerUser(User user) {
      UserDaoImpl userDao=new UserDaoImpl();
       //随机生成一个邮箱验证码
        user.setCode(UUID.randomUUID().toString().replace("-",""));
        final boolean registerState = userDao.registeredUser(user);
        if(registerState==true){
            //使用异步方式向用户发送邮件
            EmailUtils.sendEmail(user);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 登录验证
     * @param username
     * @param password
     * @return
     */
    @Override
    public User userLogin(String username,String password) {
        UserDaoImpl userDao=new UserDaoImpl();
        //根据用户名查询数据库信息，返回一个User对象
        User user=  userDao.findByUsername(username);
        //登录时将输入的密码转换为MD5与数据库中的值进行比较
        password=MD5Utils.md5(password);


        //如果User对象不为空，则获取user对象内的password数据
        if (user!=null){
            final String password1 = user.getPassword();//获取密码
           if (!password1.isEmpty()){
               final boolean result = password1.equals(password);
               return user;
           }else{
               return null;
           }
        }
        return null;
    }

    /**
     * 用户激活
     * @param email
     * @param code
     * @return
     */
    @Override
    public boolean activeUser(String email, String code) {
        boolean result=false;
        //调用dao
        UserDaoImpl userDao=new UserDaoImpl();
        boolean queryResult= userDao.activeQuery(email,code);
        if (queryResult==true){
            result =  userDao.updateFlag(email,code);
            if (result==true)
                return true;
            return  false;
        }
        return false;
    }

    @Override
    public List<TbAddress> queryAddress(int uid) {
        //调用dao
        UserDaoImpl userDao=new UserDaoImpl();


        return userDao.queryAddressByUid(uid);
    }


}
